from sqlmodel import Session, select, desc
from pydantic import ValidationError
from db.schemas.bs_mode_schemas import IBaseStationCreate, ILTEFreqRecordCreate
from .bs_models import BaseStation, LTEFreqRecord


# 根据基站id，模糊查询基站
def query_bs_by_id(db: Session, id: int) -> BaseStation:
    return db.get(BaseStation, id)


# 根据基站名称，模糊查询基站表，返回所有数据
def query_bs_by_name(db: Session, name: str) -> list[BaseStation]:
    stmt = (
        select(BaseStation)
        .where(BaseStation.name.like(f"%{name}%"))
        .order_by(desc(BaseStation.create_datetime))
    )
    return db.exec(stmt).all()


def get_bs_all(db: Session):
    # return db.exec(select(BaseStation)).all()[:10]
    return db.exec(select(BaseStation)).all()


def get_lte_bs_all(db: Session, bs_id: int):
    """
    获取基站对应的所有的LTE基站
    """
    stmt = select(LTEFreqRecord).where(LTEFreqRecord.base_station_id == bs_id)
    return db.exec(stmt).all()


def create_base_station(
    db: Session, basestation_create: IBaseStationCreate
) -> BaseStation:
    try:
        bs_dict = basestation_create.model_dump()
        # 转换为字典并重新实例化（触发验证）
        validated_bs = IBaseStationCreate(**bs_dict)
        # 验证通过后，创建BaseStation
        bs = BaseStation(**bs_dict)
        db.add(bs)
        db.commit()
        db.refresh(bs)
        return bs
    except ValidationError as e:
        print(e)


def create_lte_freq_record(
    db: Session, lte_frecord_create_obj: ILTEFreqRecordCreate
) -> LTEFreqRecord:
    try:
        lte_dict = lte_frecord_create_obj.model_dump()
        # Bug修复：此处应该使用 ILTEFreqRecordCreate 而非 IBaseStationCreate
        validated_lte = ILTEFreqRecordCreate(**lte_dict)
        # 验证通过后，创建 LTEFreqRecord
        record = LTEFreqRecord(**validated_lte)
        db.add(record)
        db.commit()
        db.refresh(record)
        return record
    except Exception as e:
        db.rollback()
        raise e


def get_lte_freq_record(db: Session, base_station: BaseStation) -> list[LTEFreqRecord]:
    """
    根据基站对象查询对应的 LTEFreqRecord 记录
    :param db: 数据库会话
    :param base_station: 基站对象
    :return: 对应的 LTEFreqRecord 记录列表
    """
    stmt = select(LTEFreqRecord).where(LTEFreqRecord.base_station_id == base_station.id)
    return db.exec(stmt).all()
